package com.huyi.common.config;

import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 线程池配置，主要作用在于Spring启动时自动加载一个ExecutorService对象.
 * @EnableAsync 放在主类中，默认加载，也可以如下面指定配置加载
 * 
 * @author shengli.hu
 * @date 2018/08/09
 */
@Configuration
@ComponentScan("com.huyi")  
@EnableAsync // 开启异步机制
// @ConditionalOnProperty(name = "enabled", havingValue = "false") // 未开启加载
public class AsyncConfig implements AsyncConfigurer {

	// 执行需要依赖线程池，这里就来配置一个线程池
	@Bean
	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		//核心线程池数量
		executor.setCorePoolSize(50);
		//最大线程数量
		executor.setMaxPoolSize(100);
		//设置线程前缀
		executor.setThreadNamePrefix("Executor-Aysnc-");
		//线程池的队列容量
		executor.setQueueCapacity(150);
		executor.initialize();
		return executor;
	}
	
	/*异步任务中异常处理*/
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}